#include<stdio.h>
#define maxsize 100
typedef struct sqqueue
{
	int data[maxsize];
	int front; //队首
	int rear;//队尾
} SQQUEUE;
int InitQueue(SQQUEUE *p) /*初始化队列*/
{
	p->front=0;
	p->rear=0;
	return 1;
}
int EnQueue(SQQUEUE *q, int e) /*入队*/
{
	if((q->rear+1)%maxsize==q->front)//判断队列是否满
	return 0;
	else
	q->data[q->rear]=e;//加入一个新的数据
	q->rear=(q->rear+1)%maxsize;//将队尾数加1
	return 1;
}
int DeQueue(SQQUEUE *q)/*出队*/
{
	int e;
	if (q->front==q->rear)//判断队列是否为空
	return 0;
	e=q->data[q->front];//提出队首数据
	q->front=(q->front+1)%maxsize;//改变队首
	return e;
}
int Empty(SQQUEUE *q)/*判断队列是否空*/
{
	int v;
	if (q->front==q->rear)//判断队列是否为空，
	v=1;
	else
	v=0;
	return v; 
}
int QueueFront(SQQUEUE *q)/*获得队首元素*/
{
	int e;
	if (q->front==q->rear) //判断队列是否为空
	e=1;
	else
	e=q->data[q->front];
	return e;
}
int QueueBack(SQQUEUE *q)
{
	int e;
	if(q->front == q->rear)
		e = -1;
	else 
		e = q->data[q->rear-1];
	return e;
}
void Display(SQQUEUE *q)/*从队首到队尾显示队列中的元素*/
{
	int s;
	s=q->front;
	printf("队列中的元素为:\n");
	if (q->front==q->rear)
	printf("队列为空!");
	else
	{
		while(s<q->rear)
		{
		printf(" %d <-", q->data[s]);
		s=(s+1)%maxsize;
		}
		printf("\n");
	}
}

int queue()
{
	SQQUEUE queue,*head;
	int x,y,select;
	char ch='y';
	head=&queue;
	InitQueue(head);
	printf("一个空队列已经创建!\n");
	while(ch=='y' || ch=='Y')
	{
		printf("1: 入队列 \n");
		printf("2: 出队列 \n");
		printf("3: 判断队列是否空 \n");
		printf("4: 取队首元素 \n");
		printf("5: 取队尾元素 \n");
		printf("6: 显示队列\n");
		printf("请选择功能 (1～4):");
		scanf("%d",&select);
		switch(select)
		{
			case 1:
			{ 
				printf("请输入一个值: ");
				scanf("%d",&x);
				EnQueue(head,x);
				Display(head);
				break;
			}
			case 2:
			{
				DeQueue(head);
				Display(head);
				break;
			}
			case 3:
			{
				if(Empty(head))
				printf("队列为空\n");
				else
				printf("队列不空\n");
				break;
			}
			case 4:
			{
				y=QueueFront(head);
				if(y)
					printf("队列为空");
				else
					printf("队首元素为: %d\n",y);
				Display(head);
				break;
			}
			case 5:
			{
				y = QueueBack(head);
				if(y == -1)
					printf("队列为空\n");
				else
					printf("队尾元素为: %d\n",y);
				Display(head);
				break;
			}
			case 6:
			{
				Display(head);
			}
		}
		printf("是否继续？(y/n)");
		while(getchar()!='\n');
		ch=getchar();
		while(getchar()!='\n');
	}
	return 0;
}


int main(int argc,char **argv)
{
	queue();
	return 0;
}
